<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<c:set var="ctx" value="<%=basePath%>" />
<!DOCTYPE html>
<html lang="en">

<head>
    <base href="<%=basePath%>">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <meta name="format-detection" content="telephone=no, email=no">
    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="renderer" content="webkit">
    <meta http-equiv="keywords" content="云净,透析单,网页透析" />
    <meta http-equiv="description" content="云净透析单" />
    <link href="image/yunjing/logo.ico" type="image/x-icon" rel="shortcut icon">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/common/base.css" />
    <link rel="stylesheet" type="text/css" href="css/yunjing/mtxform.css?v=201708311653" />
    <link rel="stylesheet" type="text/css" href="css/yunjing/iconfont/mtx_hzgl/iconfont.css" />
    <link rel="stylesheet" href="js/swiper/swiper.min.css">
    <title>云净_上传检验检查图片</title>
    <style>
        body {
            overflow-x: hidden;
            background: #f8f8f8;
        }
    </style>
</head>

<body>
    <div id="body">
        <div style="height: 50px; line-height: 50px;text-align: center;border-bottom: 1px solid #171E28;">
            上传图片:
            <input type="file" accept="image/jpeg,image/jpg,image/png" id="uploadImage" onchange="selectFileImage(this);" />
        </div>
        <div style="margin-top: 10px;">
            <img alt="preview" id="myImage" />
        </div>
    </div>
    <script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="js/jquery/mobile/jquery.mobile.custom.min.js"></script>
    <script type="text/javascript" src="js/layer/layer.js"></script>
    <script type="text/javascript" src="js/upload/mobileBUGFix.mini.js"></script>
    <script type="text/javascript" src="js/upload/exif.js"></script>
    <script>
        $(function () {
            $.ajaxSetup({
                async: false
            });
            getOSSAuth()
        })

        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(',')[1]); //去掉url的头，并转换为byte
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }
            return new Blob([ab], {
                type: 'image/png'
            });
        }


        var accessid = '',
            policy = '',
            Signature = '',
            key = "xgtl/1162/test0328.png",
            host = '',
            expire = 0,
            now = 0;
        //获取授权
        function getOSSAuth() {
            now = Date.parse(new Date()) / 1000;
            if (expire < now + 3) {
                $.post("http://192.168.1.115:8080/yunjingservice/OSSAuth/yjxgtl.shtml", function (data) {
                    accessid = data.accessid;
                    policy = data.policy;
                    signature = data.signature;
                    expire = data.expire;
                    host = data.host;
                });
            }
        }

        //获取文件后缀名 
        function get_suffix(filename) {
            pos = filename.lastIndexOf('.')
            suffix = ''
            if (pos != -1) {
                suffix = filename.substring(pos)
            }
            return suffix;
        }

        function upload(blob) {

            getOSSAuth(); //获取授权
            var request = new FormData();
            request.append('OSSAccessKeyId', accessid);
            request.append('policy', policy);
            request.append('Signature', signature);
            request.append('key', key); //+filename
            request.append('success_action_status', '200'); //status头，如果不设置返回的是204
            request.append('Access-Control-Allow-Origin', '*');
            request.append('Access-Control-Allow-Methods', 'GET, POST');
            request.append('file', blob);
            $.ajax({
                url: host,
                data: request,
                processData: false,
                cache: false,
                async: false,
                contentType: false,
                //关键是要设置contentType 为false，不然发出的请求头 没有boundary
                type: "POST",
                beforeSend: function () {},
                success: function (data, textStatus, request) {
                    if (request.status == '200') {
                        layer.msg("图片上传成功");
                    }

                    var time = Date.parse(new Date());
                    $("img").attr("src",
                        "https://biangene.oss-cn-shenzhen.aliyuncs.com/xgtl/1162/test0328.png?x-oss-process=image/resize,w_600,h_800/quality,Q_100&tag=" +
                        time);
                },
                error: function (data, textStatus, request) {
                    layer.msg("上传失败，请重试！");
                },
                complete: function () {}
            });
        }

        function selectFileImage(fileObj) {
            var file = fileObj.files['0'];
            //图片方向角 added by lzk
            var Orientation = null;

            if (file) {
                var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
                if (!rFilter.test(file.type)) {
                    layer.msg("请选择jpeg、png格式的图片");
                    return;
                }

                //获取照片方向角属性，用户旋转控制
                EXIF.getData(file, function () {
                    EXIF.getAllTags(this);
                    Orientation = EXIF.getTag(this, 'Orientation');
                });

                var oReader = new FileReader();
                oReader.onload = function (e) {
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var expectWidth = this.naturalWidth;
                        var expectHeight = this.naturalHeight;

                        if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                            expectWidth = 800;
                            expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                        } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight >
                            1200) {
                            expectHeight = 1200;
                            expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                        }
                        //console.log(expectWidth + ',' + expectHeight);
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");
                        canvas.width = expectWidth;
                        canvas.height = expectHeight;
                        ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                        //console.log(canvas.width + ',' + canvas.height);

                        var base64 = null;
                        var mpImg = new MegaPixImage(image);
                        mpImg.render(canvas, {
                            maxWidth: 800,
                            maxHeight: 1200,
                            quality: 0.8,
                            orientation: Orientation
                        });

                        base64 = canvas.toDataURL("image/jpeg", 0.8);

                        //var img = 
                        //修复ios
                        if (navigator.userAgent.match(/iphone/i)) {
                            //console.log(expectWidth + ',' + expectHeight);
                            //如果方向角不为1，都需要进行旋转 added by lzk
                            if (Orientation != "" && Orientation != 1) {
                                //console.log('旋转处理');
                                switch (Orientation) {
                                    case 6: //需要顺时针（向左）90度旋转
                                        //console.log('需要顺时针（向左）90度旋转');
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8: //需要逆时针（向右）90度旋转
                                        //console.log('需要顺时针（向右）90度旋转');
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3: //需要180度旋转
                                        //console.log('需要180度旋转');
                                        rotateImg(this, 'right', canvas); //转两次
                                        rotateImg(this, 'right', canvas);
                                        break;
                                }
                            }

                            var mpImg = new MegaPixImage(image);
                            mpImg.render(canvas, {
                                maxWidth: 800,
                                maxHeight: 1200,
                                quality: 0.8,
                                orientation: Orientation
                            });
                            base64 = canvas.toDataURL("image/jpeg", 0.8);
                        } else if (navigator.userAgent.match(/Android/i)) { // 修复android
                            var encoder = new JPEGEncoder();
                            base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth,
                                expectHeight), 80);
                        } else {
                            //console.log(Orientation);
                            if (Orientation != "" && Orientation != 1) {
                                //console.log('旋转处理');
                                switch (Orientation) {
                                    case 6: //需要顺时针（向左）90度旋转
                                        //console.log('需要顺时针（向左）90度旋转');
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8: //需要逆时针（向右）90度旋转
                                        //console.log('需要顺时针（向右）90度旋转');
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3: //需要180度旋转
                                        //console.log('需要180度旋转');
                                        rotateImg(this, 'right', canvas); //转两次
                                        rotateImg(this, 'right', canvas);
                                        break;
                                }
                            }
                            var mpImg = new MegaPixImage(image);
                            mpImg.render(canvas, {
                                maxWidth: 800,
                                maxHeight: 1200,
                                quality: 0.8,
                                orientation: Orientation
                            });

                            base64 = canvas.toDataURL("image/jpeg", 0.8);
                        }
                        //convertBase64UrlToBlob(base64)
                        canvas.toBlob(function (blob) {
                            upload(blob)

                        }, 'image/png');

                        $("#myImage").attr("src", base64);
                    };
                };
                oReader.readAsDataURL(file);
            }
        }


        //对图片旋转处理 added by lzk
        function rotateImg(img, direction, canvas) {
            //console.log(img);
            //最小与最大旋转方向，图片旋转4次后回到原方向  
            var min_step = 0;
            var max_step = 3;

            if (img == null) return;

            var height = canvas.height;
            var width = canvas.width;
            //console.log(width + ',' + height);

            var step = 2;
            if (step == null) {
                step = min_step;
            }
            if (direction == 'right') {
                step++;
                //旋转到原位置，即超过最大值  
                step > max_step && (step = min_step);
            } else {
                step--;
                step < min_step && (step = max_step);
            }

            //旋转角度以弧度值为参数  
            var degree = step * 90 * Math.PI / 180;
            var ctx = canvas.getContext('2d');
            switch (step) {
                case 0:
                    canvas.width = width;
                    canvas.height = height;
                    ctx.drawImage(img, 0, 0);
                    break;
                case 1:
                    canvas.width = height;
                    canvas.height = width;
                    ctx.rotate(degree);
                    ctx.drawImage(img, 0, -height);
                    break;
                case 2:
                    canvas.width = width;
                    canvas.height = height;
                    ctx.rotate(degree);
                    ctx.drawImage(img, -width, -height);
                    break;
                case 3:
                    canvas.width = height;
                    canvas.height = width;
                    ctx.rotate(degree);
                    ctx.drawImage(img, -width, 0);
                    break;
            }
        }
    </script>
</body>

</html>